from flask import Blueprint, render_template, jsonify, request, abort, session, make_response
from models.entity.module import Module
import json
import functools
# functools.wraps()
from utils.result import result
from models.view.auth import AuthLogicalModel

"""
这个文件完成的是对模块的管理，实现对模块的添加，删除和修改,查看
"""
mod = Blueprint("core_module", __name__, url_prefix="/core/module", template_folder="templates", static_folder="static")


@mod.route('/', methods=["GET"])
def index(*args, **kargs):
    return render_template('/admin/core/moduleManagementT.html', **locals())

# 返回除顶级的模块返回所有模块的列表,带children形式
@mod.route("/get_tree_first_page/", methods=["GET", "POST"])
def get_tree_first_page():
    # return result(success=1, data=session["auth"]["modules"])
    return result(success=1,data=Module().get_tree_by_pid(1))


# 返回顶级菜单下的第一层模块,(5个模块),hairy8月14加
@mod.route("/get_first_page/", methods=["GET", "POST"])
def get_first_page():
    # return result(success=1, data=session["auth"]["modules"])
    return result(success=1, data=Module.get_module_by_pid())





# 以带children的形式返回所有模块,顶级菜单也返回
@mod.route("/get_tree/", methods=["GET", "POST"])
def get_tree_json():
    ret_list = Module().get_tree(0)
    return result(success=1,data=ret_list)

# 返回包括第一级模块在内的所有模块的列表,不区分levle,不带children,没有进行递归,并列返回
@mod.route("/get_all/", methods=["GET", "POST"])
def get_all():
    """返回模块列表，这个方法可能压根就用不上,用post"""
    # 请求数据格式：无
    data = [p.to_dict() for p in Module().get_list_all()]
    return result(success=1, data=data)


@mod.route("/get_children_by_module_id/", methods=["POST", "GET"])
def get_children_by_module_id():
    """
    根据模块id获取特定模块的子模块的列表
    """
    # request: json
    # {
    #       "id":id
    # }
    if request.method == "POST":
        data = json.loads(request.data.decode("utf-8"))
        # module_id = data["pid"]
        pid = data.get('pid')
        ret_list = Module().get_tree(pid)
        return result(success=1, data=ret_list)
    elif request.method == "GET":
        parent_id = request.args.get("pid", type=int)
        ret_list = Module().get_tree_by_pid(parent_id)
        return result(success=1, data=ret_list)
    else:
        return abort(405)


@mod.route("/del/", methods=["POST"])
def del_module():
    """删除模块列表,如果有子类，则不能删除"""   # 已测,管用
    # 删除成功相应 {res：}
    rev_data = json.loads(request.data.decode("utf-8"))
    rev_id = int(rev_data['id'])
    module = Module().get_entity_by_id(rev_id)
    if module is None:
        return result(success=0, error_code=-1, error_msg="指定模块不存在")
    if len(Module().get_list_by_pid(rev_id)) != 0:
        # print(len(Module().get_list_by_pid(rev_id)))
        # for i in Module().get_list_by_pid(rev_id):
        #     print(i.id)
        return result(success=0, error_code=-1, error_msg="模块存在子节点,不能删除")
    if module.delete():
        # AuthLogicalModel(session).update_redis()
        return result(success=1)
    else:
        return result(success=0,error_code=-2,error_msg="未知错误")


@mod.route("/add/", methods=["POST", "GET"])
# def add_module(*args, **kargs):
def add_module():
    """增加模块列表"""   # 已测,管用
    """
    {
    "name":"lihongzhi",
    "url":"ddddd",
    "code":"d",
    "target":"kkkk",
    "icon":"ddd",
    "is_menu":1,
    "is_public":1,
    "status":0,
    "is_expand":2,
    "dis_order":2,
    "ParentId":0,
    "description":"ffffff"
    }
    """
    # try:
    #     if request.method == 'POST':
    #         print(111111111,request.data)
    #         d = json.loads(request.data.decode("utf-8"))
    #         print('dict',d)
    # except:
    #     error_msg = {
    #         "success": 0,
    #         "error_code": -1,
    #         "error_msg": "json format error"
    #     }
    #     return jsonify(error_msg)
    data = json.loads(request.data.decode("utf-8"))
    print('data',data)
    if 'id' in data:
        data.pop('id')
    module = Module()
    try:
        module.from_dict(data)
    except RuntimeError as e:
        return result(success=0,error_code=-1, error_msg=str(e))
    # print(d)
    print('module.id', module.id)
    parent_id = data["parent_id"]
    # if parent_id not in [p["id"] for p in session["auth"]["module_list"]]:
    #     # 如果添加到了一个其没有访问权限的位置
    #     return abort(403)
    depth = Module().get_entity_by_id(parent_id).depth  # 父节点的深度
    same_level_modules = Module.get_modules_by_depth(depth)  # 和父节点同一级的深度
    for item in same_level_modules:
        if item.name == data["name"]:
            return result(success=0, error_code=-1, error_msg="该模块名字已被占用")
    if Module.get_module_by_code(data["code"]):
        return result(success=0,error_code=-2,error_msg="该模块编码已被占用")
    if module.save():
        # AuthLogicalModel(session).update_redis()
        return result(success=1)
    else:
        return result(success=0,error_code=-3,error_msg="未知错误")


@mod.route("/edit/", methods=["POST"])
def edit_module_interface():
    """
    修改模块信息     # 已测,管用
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0,error_code=-1,error_msg="json format error")
    # if data["id"] not in [p["id"] for p in session["auth"]["module_list"]]:
    #     return abort(403)
    # module = Module.query.filter_by(id=data["id"]).first()
    module = Module().get_entity_by_id(data["id"])
    # module = Module.query.filter_by(id=data.get('id', '')).first()
    print('旧的', module.parent_id)
    old_parent_id= module.parent_id

    if data["name"] != module.name and Module.query.filter_by(parent_id=data["parent_id"]).filter_by(name=data["name"]).first():
        return result(success=0,error_code=-1,error_msg="同级模块不可重名")
    try:
        module.from_dict(data)
    except RuntimeError as e:
        return result(success=0,error_code=-1,error_msg=str(e))
    # res = False
    try:

        print('新的', module.parent_id)
        res = module.save()
    except RuntimeError as e:
        return result(success=0,error_code=-2,error_msg=str(e))
    if res is False:
        return result(success=0,error_code=-2,error_msg="保存错误")
    else:
        # AuthLogicalModel(session).update_redis()
        return result(success=1)


#这个是做了一个兼容,后面加不加/都可以
@mod.route("/search/", methods=["POST","GET"])
@mod.route("/search", methods=["POST","GET"])
def module_search():
    """
    模糊搜索接口   # 已测,管用
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        if request.method == "POST":
            print(111)
            data = json.loads(request.data.decode("utf-8"))
            print(data)
    except:
        return result(success=0,error_code=-1,error_msg="json格式错误")
    # print('开始')
    # print('request.data', request.data)
    # print('request.data', request.get_json())
    # data = json.loads(request.data.decode("utf-8"))
    # data = json.loads(request.get_json().decode("utf-8"))
    try:
        if request.method == "GET":
            print(111)
            data = json.loads(request.args.decode("utf-8"))
            print(data)
    except:
        return result(success=0,error_code=-1,error_msg="参数错误")

    print('data', data)
    if "query_word" in data:
        query_word = data["query_word"]
        # print('query_word',query_word)
    else:
        return result(success=0,error_code=-2,error_msg="数据不完整")
    rdic = Module.search(query_word)
    print(1111111111)
    print(rdic)
    print(2222222222)
    return jsonify(rdic)
